"""
通知管理相关 API 路由
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional
from models.m import Notification, User
from schemas.notification_schemas import (
    NotificationCreate,
    NotificationUpdate,
    NotificationResponse,
    NotificationListResponse,
)
from utils.auth import get_current_user
import logging

logger = logging.getLogger(__name__)

notifications_router = APIRouter(prefix="/api/notifications", tags=["通知管理"])


@notifications_router.get("", response_model=NotificationListResponse)
async def get_notifications(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    is_read: Optional[bool] = Query(None, description="是否已读筛选"),
    type: Optional[str] = Query(None, description="通知类型筛选"),
    current_user: User = Depends(get_current_user)
):
    """
    获取当前用户的通知列表（分页）
    """
    try:
        # 构建查询条件
        query = Notification.filter(user_id=current_user.id)
        
        # 添加筛选条件
        if is_read is not None:
            query = query.filter(is_read=is_read)
        if type:
            query = query.filter(type=type)
        
        # 获取总数
        total = await query.count()
        
        # 获取未读数量
        unread_count = await Notification.filter(
            user_id=current_user.id,
            is_read=False
        ).count()
        
        # 分页查询
        offset = (page - 1) * page_size
        notifications = await query.offset(offset).limit(page_size).all()
        
        # 转换为响应格式
        items = [
            NotificationResponse(
                id=n.id,
                user_id=n.user_id,
                title=n.title,
                content=n.content,
                type=n.type,
                is_read=n.is_read,
                status=n.status,
                extra_data=n.extra_data,
                created_at=n.created_at,
                updated_at=n.updated_at
            )
            for n in notifications
        ]
        
        return NotificationListResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=items,
            unread_count=unread_count
        )
    
    except Exception as e:
        logger.error(f"❌ 获取通知列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取通知列表失败: {str(e)}")


@notifications_router.get("/unread-count")
async def get_unread_count(current_user: User = Depends(get_current_user)):
    """
    获取当前用户的未读通知数量
    """
    try:
        count = await Notification.filter(
            user_id=current_user.id,
            is_read=False
        ).count()
        
        return {"code": 200, "data": {"count": count}}
    
    except Exception as e:
        logger.error(f"❌ 获取未读数量失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取未读数量失败: {str(e)}")


@notifications_router.get("/{notification_id}", response_model=NotificationResponse)
async def get_notification_detail(
    notification_id: int,
    current_user: User = Depends(get_current_user)
):
    """
    获取通知详情（并自动标记为已读）
    """
    try:
        notification = await Notification.filter(
            id=notification_id,
            user_id=current_user.id
        ).first()
        
        if not notification:
            raise HTTPException(status_code=404, detail="通知不存在")
        
        # 自动标记为已读
        if not notification.is_read:
            notification.is_read = True
            await notification.save()
        
        return NotificationResponse(
            id=notification.id,
            user_id=notification.user_id,
            title=notification.title,
            content=notification.content,
            type=notification.type,
            is_read=notification.is_read,
            status=notification.status,
            extra_data=notification.extra_data,
            created_at=notification.created_at,
            updated_at=notification.updated_at
        )
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ 获取通知详情失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取通知详情失败: {str(e)}")


@notifications_router.post("", response_model=NotificationResponse)
async def create_notification(
    data: NotificationCreate,
    current_user: User = Depends(get_current_user)
):
    """
    创建通知（管理员功能，可根据需要添加权限验证）
    """
    try:
        # 验证目标用户是否存在
        target_user = await User.filter(id=data.user_id).first()
        if not target_user:
            raise HTTPException(status_code=404, detail="目标用户不存在")
        
        # 创建通知
        notification = await Notification.create(
            user_id=data.user_id,
            title=data.title,
            content=data.content,
            type=data.type,
            status=data.status,
            extra_data=data.extra_data
        )
        
        # TODO: 通过 WebSocket 推送实时通知
        # await ws_manager.send_notification(data.user_id, notification)
        
        return NotificationResponse(
            id=notification.id,
            user_id=notification.user_id,
            title=notification.title,
            content=notification.content,
            type=notification.type,
            is_read=notification.is_read,
            status=notification.status,
            extra_data=notification.extra_data,
            created_at=notification.created_at,
            updated_at=notification.updated_at
        )
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ 创建通知失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"创建通知失败: {str(e)}")


@notifications_router.patch("/{notification_id}/read")
async def mark_as_read(
    notification_id: int,
    current_user: User = Depends(get_current_user)
):
    """
    标记单个通知为已读
    """
    try:
        notification = await Notification.filter(
            id=notification_id,
            user_id=current_user.id
        ).first()
        
        if not notification:
            raise HTTPException(status_code=404, detail="通知不存在")
        
        notification.is_read = True
        await notification.save()
        
        return {"code": 200, "msg": "已标记为已读"}
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ 标记已读失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"标记已读失败: {str(e)}")


@notifications_router.patch("/mark-all-read")
async def mark_all_as_read(current_user: User = Depends(get_current_user)):
    """
    标记所有通知为已读
    """
    try:
        await Notification.filter(
            user_id=current_user.id,
            is_read=False
        ).update(is_read=True)
        
        return {"code": 200, "msg": "已全部标记为已读"}
    
    except Exception as e:
        logger.error(f"❌ 批量标记已读失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"批量标记已读失败: {str(e)}")


@notifications_router.delete("/{notification_id}")
async def delete_notification(
    notification_id: int,
    current_user: User = Depends(get_current_user)
):
    """
    删除单个通知
    """
    try:
        notification = await Notification.filter(
            id=notification_id,
            user_id=current_user.id
        ).first()
        
        if not notification:
            raise HTTPException(status_code=404, detail="通知不存在")
        
        await notification.delete()
        
        return {"code": 200, "msg": "通知已删除"}
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"❌ 删除通知失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"删除通知失败: {str(e)}")


@notifications_router.delete("/clear-all")
async def clear_all_notifications(current_user: User = Depends(get_current_user)):
    """
    清空所有通知
    """
    try:
        deleted_count = await Notification.filter(user_id=current_user.id).delete()
        
        return {
            "code": 200,
            "msg": f"已清空所有通知",
            "data": {"deleted_count": deleted_count}
        }
    
    except Exception as e:
        logger.error(f"❌ 清空通知失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清空通知失败: {str(e)}")


@notifications_router.delete("/clear-read")
async def clear_read_notifications(current_user: User = Depends(get_current_user)):
    """
    清空已读通知
    """
    try:
        deleted_count = await Notification.filter(
            user_id=current_user.id,
            is_read=True
        ).delete()
        
        return {
            "code": 200,
            "msg": f"已清空所有已读通知",
            "data": {"deleted_count": deleted_count}
        }
    
    except Exception as e:
        logger.error(f"❌ 清空已读通知失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清空已读通知失败: {str(e)}")


















